//
//  WCarouselView.m
//  WCarouselView
//
//  Created by Wanglele on 16/4/25.
//  Copyright © 2016年 Wanglele. All rights reserved.
//

#import "WCarouselView.h"

typedef enum : NSUInteger
{
    WTurnDirectionNone,             //没有动
    WTurnDirectionClockwise,        //顺时针
    WTurnDirectionAnticlockwise     //逆时针
} WTurnDirection;

@interface WCarouselView()<UIScrollViewDelegate>

//轮播子视图
@property(nonatomic,strong)NSMutableArray * carouseItemViews;
//用于放轮播子视图的UIScrollView
@property(nonatomic,strong)UIScrollView * showSv;
//当前显示的View
@property(nonatomic,strong)UIView * currentShowView;
//下一视图
@property(nonatomic,strong)UIView * nextShowView;
//上一视图(目前没用到这个)
@property(nonatomic,strong)UIView * previousShowView;

//当前转动的方向,顺时针/逆时针,默认WTurnDirectionNone
@property(nonatomic,assign)WTurnDirection direction;

//当前显示图片索引
@property(nonatomic,assign)NSInteger currentIndex;
//将要显示图片索引
@property (nonatomic, assign) NSInteger nextIndex;


@property(nonatomic,strong)NSTimer * timer;


@end



@implementation WCarouselView

- (void)awakeFromNib{
    [super awakeFromNib];
    self.carouseItemViews = [NSMutableArray array];
    self.currentIndex = 0;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.carouseItemViews = [NSMutableArray array];
        self.currentIndex = 0;
    
    }
    return self;
}

/**
 *  初始化,且设置滚动方向
 *
 *  @param frame     位置大小
 *  @param direction 滚动方向
 *
 */
-(instancetype)initWithFrame:(CGRect)frame ScrollingDirection:(WScrollingDirection)direction
{
    self = [self initWithFrame:frame];
    self.scrollingDirection = direction;
    self.currentShowView.backgroundColor = [UIColor clearColor];
    self.showSv.backgroundColor = [UIColor clearColor];

    return self;
}

-(void)reloadData
{
    [self setNeedsLayout];
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    [self addSubview:self.showSv];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    //有导航控制器时，会默认在scrollview上方添加64的内边距，这里强制设置为0
    self.showSv.contentInset = UIEdgeInsetsZero;
    self.showSv.frame = self.bounds;
    
    if ([self.delegate respondsToSelector:@selector(numberOfItemsInCarouseView:)])
    {
        NSInteger number = [self.delegate numberOfItemsInCarouseView:self];
        CGFloat svWidth = self.showSv.frame.size.width;
        CGFloat svHeight = self.showSv.frame.size.height;
        self.currentShowView.frame = (CGRect){svWidth,0,svWidth,svHeight};
        if (number <= 1)
        {
            self.showSv.scrollEnabled = NO;
        }
        if ([self.delegate respondsToSelector:@selector(carouseView:indexOfItem:)])
        {
            [self.carouseItemViews removeAllObjects];
            for (int i = 0; i < number; i ++)
            {
                UIView * itemView = [self.delegate carouseView:self indexOfItem:i];
                [self.carouseItemViews addObject:itemView];
                
                if (i == 0)
                {
                    if (itemView.superview != self.currentShowView)
                    {
                        [self removeAllSubviewWithSuperView:self.currentShowView];
                        itemView.frame = self.currentShowView.bounds;
                        [self.currentShowView addSubview:itemView];
                    }
                }
            }
        }
    }
    
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCurrentShowView:)];
    [self.currentShowView addGestureRecognizer:tapGesture];
    
//    self.currentShowView 
    
    //设置ScrollView相关的
    [self configScrollViewContentSize];
    [self startTimer];
}

-(void)tapCurrentShowView:(UITapGestureRecognizer *)gesture
{
    if ([self.delegate respondsToSelector:@selector(numberOfItemsInCarouseView:)])
    {
        NSInteger number = [self.delegate numberOfItemsInCarouseView:self];
        if (number != 0)
        {
            if ([self.delegate respondsToSelector:@selector(carouseView:indexOfItemWhenClick:)])
            {
                [self.delegate carouseView:self indexOfItemWhenClick:self.currentIndex];
            }
        }
    }
}

-(void)didMoveToSuperview
{
    [super didMoveToSuperview];
    
    
}

-(void)configScrollViewContentSize
{
    if ([self.delegate respondsToSelector:@selector(numberOfItemsInCarouseView:)])
    {
        NSInteger number = [self.delegate numberOfItemsInCarouseView:self];
        CGFloat svWidth = self.showSv.frame.size.width;
        CGFloat svHeight = self.showSv.frame.size.height;
        if (number > 0)
        {
            //总共3个，默认显示最中间的那个
            if (self.scrollingDirection == WScrollingDirectionHorizontal)
            {
                self.showSv.contentSize = CGSizeMake(svWidth * 3, 0);
                self.currentShowView.frame = CGRectMake(svWidth * 1, 0, svWidth, svHeight);
                self.showSv.contentOffset = (CGPoint){self.currentShowView.frame.origin.x,self.currentShowView.frame.origin.y};
            }else
            {
                self.showSv.contentSize = CGSizeMake(0, svHeight * 3);
                self.currentShowView.frame = CGRectMake(0, svHeight * 1, svWidth, svHeight);
                self.showSv.contentOffset = (CGPoint){self.currentShowView.frame.origin.x,self.currentShowView.frame.origin.y};
            }
            
        }else
        {
            self.showSv.contentSize = CGSizeZero;
            self.showSv.contentOffset = CGPointZero;
            self.currentShowView.frame = self.showSv.bounds;
        }
    }else
    {
        
    }
}

-(void)removeAllSubviewWithSuperView:(UIView *)supView
{
    if ([supView isKindOfClass:[UIView class]])   //非空
    {
        [supView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    /*
    for (UIView * subView in supView.subviews)
    {
        [subView removeFromSuperview];
    }
    */
}

-(void)changeToNextView
{
    [self removeAllSubviewWithSuperView:self.currentShowView];

    
    
    UIView * toView = [self.nextShowView.subviews lastObject];
    toView.frame = self.currentShowView.bounds;
    [self.currentShowView addSubview:toView];
    
    self.currentIndex = self.nextIndex;
    if (self.scrollingDirection == WScrollingDirectionHorizontal)
    {
        self.showSv.contentOffset = CGPointMake(self.showSv.frame.size.width, 0);
    }else
    {
        self.showSv.contentOffset = CGPointMake(0, self.showSv.frame.size.height);
    }
    
    if ([self.delegate respondsToSelector:@selector(carouseView:indexOfItemWhenDidScroll:)])
    {
        [self.delegate carouseView:self indexOfItemWhenDidScroll:self.currentIndex];
    }

}

-(void)startTimer
{
    if (self.carouseItemViews.count <= 1 || self.autoPlayTime <= 0)
    {
        return;
    }
    
    if (self.timer)
    {
        [self stopTimer];
    }
    
    self.timer = [NSTimer timerWithTimeInterval:self.autoPlayTime < 1? 3 : self.autoPlayTime target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

-(void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)nextPage
{
    if (self.scrollingDirection == WScrollingDirectionHorizontal)
    {
        [self.showSv setContentOffset:CGPointMake(self.showSv.frame.size.width*2, 0) animated:YES];
    }else
    {
        [self.showSv setContentOffset:CGPointMake(0,self.showSv.frame.size.height*2) animated:YES];
    }
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat svWidth = scrollView.frame.size.width;
    CGFloat svHeight = scrollView.frame.size.height;
    if (self.scrollingDirection == WScrollingDirectionHorizontal)
    {
        //取当前滑动的offset.x
        CGFloat offsetX = scrollView.contentOffset.x;

        //获取转动的方向
        self.direction = offsetX > svWidth * 1 ? WTurnDirectionAnticlockwise : (offsetX < svWidth * 1 ? WTurnDirectionClockwise : WTurnDirectionNone);
        
        if (self.direction == WTurnDirectionClockwise)  //如果是顺时针,往右滚动
        {
            self.nextShowView.frame = CGRectMake(CGRectGetMinX(self.currentShowView.frame) - CGRectGetWidth(self.currentShowView.frame), 0, svWidth, svHeight);
            self.nextIndex = self.currentIndex - 1;
            if (self.nextIndex < 0) self.nextIndex = self.carouseItemViews.count - 1;
            if (scrollView.contentOffset.x <= svWidth * 0)
            {
                [self changeToNextView];
            }else
            {
                UIView * toView = self.carouseItemViews[self.nextIndex];
                if (toView.superview != self.nextShowView)
                {
                    [self removeAllSubviewWithSuperView:self.nextShowView];
                    toView.frame = self.nextShowView.bounds;
                    [self.nextShowView addSubview:toView];

                }
            }
        }else if (self.direction == WTurnDirectionAnticlockwise)//如果是逆时针,往左滚动
        {
            self.nextShowView.frame = CGRectMake(CGRectGetMaxX(self.currentShowView.frame), 0, svWidth, svHeight);
            self.nextIndex = (self.currentIndex + 1) % self.carouseItemViews.count;
            if (offsetX >= svWidth * 2)
            {
                [self changeToNextView];
            }else
            {
                UIView * toView = self.carouseItemViews[self.nextIndex];
                if (toView.superview != self.nextShowView)
                {
                    [self removeAllSubviewWithSuperView:self.nextShowView];
                    toView.frame = self.nextShowView.bounds;
                    [self.nextShowView addSubview:toView];
//                    if (self.currentShowView.subviews.count == 0)
//                    {
//                        
//                    }
                }
            }
        }
    } else if (self.scrollingDirection == WScrollingDirectionVertical)
    {
        //取当前滑动的offset.y
        CGFloat offsetY = scrollView.contentOffset.y;
        self.direction = offsetY > svHeight * 1 ? WTurnDirectionAnticlockwise : (offsetY < svHeight * 1 ? WTurnDirectionClockwise : WTurnDirectionNone);
        if (self.direction == WTurnDirectionAnticlockwise)//如果是逆时针,往上滚动
        {
            self.nextShowView.frame = CGRectMake(0, CGRectGetMaxY(self.currentShowView.frame), svWidth, svHeight);
            self.nextIndex = (self.currentIndex + 1) % self.carouseItemViews.count;
            if (offsetY >= svHeight * 2)
            {
                [self changeToNextView];
            }else
            {
                UIView * toView = self.carouseItemViews[self.nextIndex];
                if (toView.superview != self.nextShowView)
                {
                    [self removeAllSubviewWithSuperView:self.nextShowView];
                    toView.frame = self.nextShowView.bounds;
                    [self.nextShowView addSubview:toView];

                }
            }

        }else if (self.direction == WTurnDirectionClockwise)  //如果是顺时针,往下滚动
        {
            self.nextShowView.frame = CGRectMake(0, CGRectGetMinY(self.currentShowView.frame) - CGRectGetHeight(self.currentShowView.frame), svWidth, svHeight);
            self.nextIndex = self.currentIndex - 1;
            if (self.nextIndex < 0) self.nextIndex = self.carouseItemViews.count - 1;
            if (scrollView.contentOffset.y <= svHeight * 0)
            {
                [self changeToNextView];
            }else
            {
                UIView * toView = self.carouseItemViews[self.nextIndex];
                if (toView.superview != self.nextShowView)
                {
                    [self removeAllSubviewWithSuperView:self.nextShowView];
                    toView.frame = self.nextShowView.bounds;
                    [self.nextShowView addSubview:toView];
                    
                }
            }
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

#pragma mark - 属性生成

-(void)setAutoPlayTime:(NSTimeInterval)autoPlayTime
{
    _autoPlayTime = autoPlayTime;
    if (_autoPlayTime > 0)
    {
        [self startTimer];
    }else
    {
        [self stopTimer];
    }
}

-(UIScrollView *)showSv
{
    if (_showSv == nil)
    {
        _showSv = [[UIScrollView alloc]init];
        _showSv.pagingEnabled = YES;
        _showSv.bounces = NO;
        _showSv.showsHorizontalScrollIndicator = NO;
        _showSv.showsVerticalScrollIndicator = NO;
        _showSv.delegate = self;
        
        [_showSv addSubview:self.nextShowView];
        [_showSv addSubview:self.previousShowView];
        [_showSv addSubview:self.currentShowView];
    }
    return _showSv;
}


-(UIView *)currentShowView
{
    if (_currentShowView == nil)
    {
        _currentShowView = [[UIView alloc]init];
    }
    return _currentShowView;
}

-(UIView *)nextShowView
{
    if (_nextShowView == nil)
    {
        _nextShowView = [[UIView alloc]init];
    }
    return _nextShowView;
}

-(UIView *)previousShowView
{
    if (_previousShowView == nil)
    {
        _previousShowView = [[UIView alloc]init];
    }
    return _previousShowView;
}






@end














